package com.inei.evaluacionemype.model.connection;

import java.io.InputStream;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;

import com.inei.evaluacionemype.R;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class Util extends SQLiteOpenHelper {

	public Context context;
	public static final String DATABASE = "emype.db";
	public static final int VERSION = 1;

	public Util(Context context, String name, CursorFactory factory, int version) {
		super(context, name, factory, version);
	}

	public Util(Context ctx) {
		super(ctx, DATABASE, null, VERSION);
		context = ctx;
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		String sql;
		InputStream in;
		Document doc;
		NodeList statements;
		int i;
		try {
			DocumentBuilder dbuilder = DocumentBuilderFactory.newInstance()
					.newDocumentBuilder();

			// Marco
			in = context.getResources().openRawResource(R.raw.sqlmarco);
			doc = dbuilder.parse(in, null);
			statements = doc.getElementsByTagName("Marco");
			for (i = 0; i < statements.getLength(); i++) {
				sql = statements.item(i).getChildNodes().item(0).getNodeValue();
				db.execSQL(sql);
			}

			// Cap01
			in = context.getResources().openRawResource(R.raw.sqlcap01);
			doc = dbuilder.parse(in, null);
			statements = doc.getElementsByTagName("Cap01");
			for (i = 0; i < statements.getLength(); i++) {
				sql = statements.item(i).getChildNodes().item(0).getNodeValue();
				db.execSQL(sql);
			}

			// Cap02_03
			in = context.getResources().openRawResource(R.raw.sqlcap02_03);
			doc = dbuilder.parse(in, null);
			statements = doc.getElementsByTagName("Cap02_03");
			for (i = 0; i < statements.getLength(); i++) {
				sql = statements.item(i).getChildNodes().item(0).getNodeValue();
				db.execSQL(sql);
			}

			// Cap04
			in = context.getResources().openRawResource(R.raw.sqlcap04);
			doc = dbuilder.parse(in, null);
			statements = doc.getElementsByTagName("Cap04");
			for (i = 0; i < statements.getLength(); i++) {
				sql = statements.item(i).getChildNodes().item(0).getNodeValue();
				db.execSQL(sql);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

	}

}
